import {
    Modal,
    Form,
    Input,
    Select,
    Upload,
    Button,
    message
} from 'antd';
import React, { Component } from 'react';
import { FormComponentProps } from 'antd/es/form';
import { RcFile } from 'antd/es/upload';

import styles from './style.less';

const FormItem = Form.Item;
const SelectOption = Select.Option;

export interface AddModelProps extends FormComponentProps {
    modelVisible: boolean;
    handleModalVisible: () => void;
    handleAdd: (values: any, file: RcFile | null) => void;
    type: {
        tid: number;
        tname: string
    }[],
    company: {
        cid: number;
        cname: string;
    }[]
}

export interface AddModelState {
    imgUrl: string | ArrayBuffer | null;
    isSize: boolean;
    file: RcFile | null
}

class AddModel extends Component<AddModelProps, AddModelState> {
    state: AddModelState = {
        imgUrl: '',
        isSize: false,
        file: null
    }

    /**
     * @description: 判断文件大小类型
     * @param {File} file 文件
     */
    beforeUpload= (file: RcFile, FileList: RcFile[]): boolean | PromiseLike<void> => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJpgOrPng) {
            message.error('只能上传JPG / PNG文件!');
        }

        if (!isLt2M) {
            message.error('图片大小不能超过2MB!');
        }

        return false;
    }

    /**
     * @description: 检测图片高度
     * @param {File} file 文件
     */
    checkImgSize= (file: RcFile): Promise<boolean> => {
        return new Promise((resolve, reject) => {
            const url = window.URL;
            const img = new Image();

            img.onload = function() {
                const isSize = img.height > 240 ? false : true;

                isSize ? resolve() : reject(new Error('图片高度不能大于240px'));
            };

            img.src = url.createObjectURL(file);
        }).then(() => {
            return true;
        }, () => {
            return false;
        });
    }

    /**
     * @description: 获取图片url
     * @param {any} info 文件信息
     */
    handleChange= (info: any) => {
        if (!info.file) return;

        this.checkImgSize(info.file).then(result => {
            this.setState({ isSize: result })

            if (result) {
                this.getBase64(info.file, imgUrl => this.setState({ imgUrl, file: info.file }));
            } else {
                message.error('图片高度不能大于240px');
            }
        });
    }

    /**
     * @description: 图片转base64
     */
    getBase64= (img: RcFile, callback: (imgUrl: string | ArrayBuffer | null) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    handleSubmit= () => {
        const { form, handleAdd } = this.props;
        const { file } = this.state;

        form.validateFields((err, values) => {
            if (!err) {
                handleAdd(values, file);
            }
        })
    }

    render() {
        const {
            modelVisible,
            form,
            handleModalVisible,
            type,
            company
        } = this.props;
        const {
            imgUrl
        } = this.state;
        return (
            <Modal
                title="新增产品"
                width={600}
                visible={modelVisible}
                onOk={this.handleSubmit}
                onCancel={() => handleModalVisible()}>
                <FormItem 
                    labelCol={{ span: 5 }} 
                    wrapperCol={{ span: 15 }} 
                    label="产品名称">
                    {form.getFieldDecorator('productName', {
                    rules: [{ 
                        required: true,
                        message: '请输入产品名称！' }]
                    })(<Input placeholder="请输入产品名称" />)}
                </FormItem>
                <FormItem 
                    labelCol={{ span: 5 }} 
                    wrapperCol={{ span: 15 }} 
                    label="产品描述">
                    {form.getFieldDecorator('productDesc', {
                    rules: [{ 
                        required: true,
                        message: '请输入产品描述！' }]
                    })(<Input placeholder="请输入产品描述" />)}
                </FormItem>
                <FormItem 
                    labelCol={{ span: 5 }} 
                    wrapperCol={{ span: 15 }} 
                    label="所属类型">
                    {form.getFieldDecorator('typeId', {
                    rules: [{ 
                        required: true,
                        message: '请选择所属类型！' }]
                    })(<Select
                        placeholder="请选择所属类型"
                        style={{ width: '100%' }}>
                        {
                            type && type.map(item => <SelectOption key={item.tid} value={item.tid}>{item.tname}</SelectOption>)
                        }
                    </Select>)}
                </FormItem>
                <FormItem 
                    labelCol={{ span: 5 }} 
                    wrapperCol={{ span: 15 }} 
                    label="所属公司">
                    {form.getFieldDecorator('companyId', {
                    rules: [{ 
                        required: true,
                        message: '请选择所属公司！' }]
                    })(<Select
                        placeholder="请选择所属公司"
                        style={{ width: '100%' }}>
                        {
                            company && company.map(item => <SelectOption key={item.cid} value={item.cid}>{item.cname}</SelectOption>)
                        }
                    </Select>)}
                </FormItem>
                <FormItem 
                    labelCol={{ span: 5 }} 
                    wrapperCol={{ span: 15 }} 
                    label="受保人年龄">
                    {form.getFieldDecorator('productAge', {
                    rules: [{ 
                        required: true,
                        message: '请输入受保人年龄！' }]
                    })(<Input placeholder="请输入受保人年龄" />)}
                </FormItem>
                <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="缴费年期">
                    {form.getFieldDecorator('productAnnual', {
                    rules: [{ 
                        required: true,
                        message: '请输入缴费年期！' }]
                    })(<Input placeholder="请输入缴费年期" />)}
                </FormItem>
                <FormItem 
                    labelCol={{ span: 5 }} 
                    wrapperCol={{ span: 15 }} 
                    label="投保金额(万)">
                    {form.getFieldDecorator('productAmount', {
                    rules: [{ 
                        required: true,
                        message: '请输入投保金额！' }]
                    })(<Input placeholder="请输入投保金额" />)}
                </FormItem>
                <FormItem 
                    labelCol={{ span: 5 }} 
                    wrapperCol={{ span: 15 }} 
                    label="产品封面">
                    {form.getFieldDecorator('file', {
                        rules: [{ 
                            required: true,
                            message: '请选择产品封面！' }]
                    })(<Upload
                        accept="image/png, image/jpg, image/jpeg"
                        showUploadList={false}
                        beforeUpload={this.beforeUpload}
                        onChange={this.handleChange}>
                        {
                            imgUrl
                            &&
                            <div className={styles.file}>
                                <img src={imgUrl as string} />
                            </div>
                        }
                        <Button>+点击上传产品封面</Button>
                    </Upload>)}
                </FormItem>
            </Modal>
        )
    }
}

export default Form.create<AddModelProps>()(AddModel);